// ignore_for_file: file_names

import 'dart:convert';
import 'dart:io';
import 'package:aitao_flutter/const/common_const.dart';
import 'package:aitao_flutter/utils/string_utils.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' hide Response, FormData, MultipartFile;
import 'package:package_info_plus/package_info_plus.dart';
import '../enum/upload_type.dart';
import '../routes/routes.dart';
import '../utils/encrypt_utils.dart';
import '../utils/sp_utils.dart';
import 'api.dart';

class RequestManager {
  final String _baseurl = 'https://api.aitaohy.com';
  final int _connectTimeout = 5;
  final int _receiveTimeout = 5;

  static RequestManager? _instance;
  late Dio _dio;
  late BaseOptions _options;

  /// 不需要加密的接口
  List<String> noSecretApiList = [API.getUploadConfig];

  /// code = 1,不需要弹出提示的文本
  List<String> noTipsMessageList = ['您尚未完成女神认证！'];

  //单例模式，只创建一次实例
  static RequestManager? getInstance() {
    if (_instance == null) {
      _instance = RequestManager();
      return _instance;
    }
    return _instance;
  }

  //构造函数
  RequestManager() {
    _options = BaseOptions(
        baseUrl: _baseurl,
        //连接时间为5秒
        connectTimeout: Duration(seconds: _connectTimeout),
        //响应时间为3秒
        receiveTimeout: Duration(seconds: _receiveTimeout),
        //默认值是"application/json; charset=utf-8",Headers.formUrlEncodedContentType会自动编码请求体.
        // contentType: Headers.formUrlEncodedContentType,
        //共有三种方式json,bytes(响应字节),stream（响应流）,plain
        responseType: ResponseType.json);
    _dio = Dio(_options);
    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (options, handler) async {
      // 在请求之前的拦截信息
      options.headers['source-id'] = Platform.isIOS ? '2' : '1';
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String version = packageInfo.version;
      String buildNumber = packageInfo.buildNumber;
      options.headers['ver_code'] = buildNumber;
      options.headers['signature'] = 'TF';
      options.headers['CFBundleVersion'] = version;
      final deviceInfoPlugin = DeviceInfoPlugin();
      final deviceInfo = await deviceInfoPlugin.deviceInfo;
      final allInfo = deviceInfo.data;
      if (StringUtils.isChinese(allInfo['name']) == false) {
        // 不包含中文
        options.headers['phone_brand'] = allInfo['name'];
      }
      options.headers['channel'] = 'AppStore';
      options.headers['uuid'] = allInfo['identifierForVendor'];
      var token = SpUtil.getToken();
      if (token.isNotEmpty) {
        options.headers['token'] = token;
      }
      // print('在请求之前的拦截信息:${options.headers}');
      return handler.next(options); //continue
    }, onResponse: (response, handler) {
      // print('响应结果:$handler');
      return handler.next(response);
      // // 在响应之前的拦截信息
      // if (response.statusCode == 200) {
      //   print('response.statusCode == 200');
      //   // 如果请求成功,状态码为200则放行
      //   return handler.next(response);
      // }
    }, onError: (DioException e, handler) {
      debugPrint("在错误之前的拦截信息:$e");
      return handler.next(e); //continue
    }));
  }

  //get请求方法
  get(url, {data, options, cancelToken, hasCode = true}) async {
    Response? response;
    try {
      response = await _dio.get(url,
          queryParameters: data, options: options, cancelToken: cancelToken);
      if (hasCode && response.data['code'] != 1) {
        EasyLoading.showToast(response.data['data'].toString());
        return null;
      }
      // if (!hasCode &&
      //     noSecretApiList.contains(url) &&
      //     response.data['StatusCode'] == 200) {
      //   return response.data;
      // }
      return response.data;
    } on DioException catch (e) {
      formatError(e);
      return null;
    }
  }

  //post请求
  post(url, {params, options, cancelToken}) async {
    Response? response;
    try {
      response = await _dio.post(url,
          data: params, options: options, cancelToken: cancelToken);
      var result = EncryptUtils.decryptAes(response.data);
      try {
        var jsonResult = json.decode(result);
        if (jsonResult['code'] != 0) {
          handelError(jsonResult);
        }
        return jsonResult;
      } catch (e) {
        return null;
      }
    } on DioException catch (e) {
      // EasyLoading.showToast(response['data']['error'].toString());
      formatError(e);
      return null;
      // throw Exception('网络异常1111');
    }
  }

  static updateOssParams() async {
    var result =
        await RequestManager().get(API.getUploadConfig, hasCode: false);
    if (result != null && result['StatusCode'] == 200) {
      SpUtil.saveOssConfig(result);
    }
  }

  handelError(Map result) {
    if (result['code'] == 1001 || result['code'] == 1401) {
      // 登录状态失效,请重新登录
      EasyLoading.showError(LoginStringConst.tokenExpiredText,
          duration: const Duration(seconds: 2));
      SpUtil.cleanUserInfo();
      Get.offAllNamed(Routes.smsCodeLoginPage);
    } else if (result['code'] == 1003) {
      var message = result['message'];
      EasyLoading.showError(message);
      // 余额不足
      // BuildContext context = Global.navigatorKey.currentState!.context;
      // AlertUtils().showAlertDialog(context, (t) {
      //   Get.toNamed(Routes.rechargePage, preventDuplicates: false);
      // }, StringStyles.lackOfSunlight.tr, StringStyles.pleaseRecharge.tr);
      // print("余额不足");
    } else {
      // code = 1不需要弹出的提示
      var message = result['message'];
      if (noTipsMessageList.contains(message)) {
        return;
      }
      EasyLoading.showError(message);
    }
  }

  //put请求
  put(url, {params, options, cancelToken}) async {
    Response? response;
    try {
      response = await _dio.put(url,
          data: params, options: options, cancelToken: cancelToken);
      if (response.data['code'] != 1) {
        EasyLoading.showToast(response.data['data'].toString());
        return null;
      }
      return response.data;
    } on DioException catch (e) {
      // print('getHttp exception: $e');
      // EasyLoading.showToast(response['data']['error'].toString());
      formatError(e);
      return null;
      // throw Exception('网络异常1111');
    }
  }

  //post Form请求
  postForm(url, {data, options, cancelToken}) async {
    Response? response;
    try {
      response = await _dio.post(url,
          options: options, cancelToken: cancelToken, data: data);
      if (response.data['code'] == 1005) {
        EasyLoading.showToast('账号密码错误');
        return null;
      }
      if (response.data['code'] != 1) {
        EasyLoading.showToast(response.data['data'].toString());
        return null;
      }
      return response.data;
    } on DioException catch (e) {
      formatError(e);
      return null;
    }
  }

  //下载文件
  downLoadFile(urlPath, savePath) async {
    Response? response;
    try {
      response = await _dio.download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        // print('$count $total');
      });
      if (response.data['code'] != 1) {
        EasyLoading.showToast(response.data['data'].toString());
      }
      // print('downLoadFile response: $response');
    } on DioException catch (e) {
      formatError(e);
    }
    return response;
  }

  // 上传单个文件
  upLoadSingleFile(String filePath, UploadImagesType type) async {
    debugPrint(type.name);
    // EasyLoading.show(status: '上传中...');
    // Response? response;
    // var formData = FormData.fromMap({
    //   'file': await MultipartFile.fromFile(
    //     filePath,
    //     filename: 'js.png',
    //   ),
    //   'type':type
    // });
    // try {
    //   response = await _dio.post(
    //     API.upload,
    //     data: formData,
    //     onSendProgress: (count, total) {
    //       if (count == total) {
    //         EasyLoading.showSuccess('上传成功');
    //       }
    //     }
    //   );
    //
    //   var result = EncryptUtils.decryptAes(response.data);
    //   try {
    //     var jsonResult = json.decode(result);
    //     if (jsonResult['code'] != 0) {
    //       handelError(jsonResult);
    //     }
    //     return jsonResult;
    //   } catch (e) {
    //     return null;
    //   }
    //
    //   return response.data;
    // } on DioException catch (e) {
    //   formatError(e);
    //   EasyLoading.dismiss();
    //   return null;
    // }
  }

  // 上传多个文件
  uploadMorFile(List<File> filePaths) async {
    EasyLoading.show(status: '上传中...');
    Response? response;
    var formData = FormData.fromMap({});

    for (int i = 0; i < filePaths.length; i++) {
      File imaeFlie = filePaths[i];
      String path = imaeFlie.path;
      var imageName = path.substring(path.lastIndexOf("/") + 1, path.length);
      var file = await MultipartFile.fromFile(path, filename: imageName);
      formData.files.add(MapEntry("file", file));
    }
    try {
      response = await _dio.post(
        API.upload,
        data: formData,
        onSendProgress: (count, total) {
          if (count == total) {
            EasyLoading.showSuccess('上传成功');
          }
        },
      );
      return response.data;
    } on DioException catch (e) {
      formatError(e);
      EasyLoading.dismiss();
      return null;
    }
  }

  //取消请求
  cancleRequests(CancelToken token) {
    token.cancel("cancelled");
  }

  void formatError(DioException e) {
    var errorStr = '请求失败';
    if (e.type == DioExceptionType.connectionTimeout) {
      errorStr = "连接超时";
    } else if (e.type == DioExceptionType.sendTimeout) {
      errorStr = "请求超时";
    } else if (e.type == DioExceptionType.receiveTimeout) {
      errorStr = "响应超时";
    } else if (e.type == DioExceptionType.badResponse) {
      errorStr = "出现异常";
    } else if (e.type == DioExceptionType.cancel) {
      errorStr = "请求取消";
    } else {
      errorStr = "未知错误";
    }
    EasyLoading.showToast(errorStr);
  }

  // 获取存在本地的token
  // authorization() async {
  //   SharedPreferences preferences = await SharedPreferences.getInstance();
  //   String? aptkn = '';
  //   aptkn = preferences.getString('aptkn');
  //   return aptkn ?? '';
  // }

  // 获取当前时间
  reqtme() {
    DateTime today = DateTime.now();
    String dateSlug =
        "${today.year.toString()}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')} ${today.hour.toString().padLeft(2, '0')}:${today.minute.toString().padLeft(2, '0')}:${today.second.toString().padLeft(2, '0')}";
    return dateSlug;
  }

  // getHeaders() async {
  //   SharedPreferences preferences = await SharedPreferences.getInstance();
  //   String? aptkn = '';
  //   aptkn = preferences.getString('aptkn');
  //   return {'apken': aptkn ?? '', 'reqtme': reqtme()};
  // }
}
